import { BASE_URL, API_WITHOUT_AUTHORIZATION, DURATION } from "@/publicConfig";
import axios from "axios";
import { fetchEventSource } from "@microsoft/fetch-event-source";
import router from "@/router";
// import { refreshToken } from "./request";
import { message } from 'ant-design-vue';
// import { useUserStore } from "@/stores/user";
import { getToken, state, clearUserInfo } from "@/stores/info"
import { onUnmounted } from 'vue'
import { lang, getAcceptLanguage, t } from "@/i18n"
import { userCheck } from '@/request/ai'
//  建立请求实例
export const instance = axios.create({
  baseURL: BASE_URL,
  timeout: 10000
})

instance.interceptors.request.use(
  (config) => {
    config.headers['token'] = getToken()
    config.headers['Accept-Language'] = getAcceptLanguage()
    return config
  },
  (error) => {
    return Promise.reject(error);
  }
);

instance.interceptors.response.use(r => { 
  const code = r.data?.code
  switch (code) {
    case 500: 
      message.error(r?.data?.message || r)
      return false
    case 401:
      message.error(r?.data?.message || r.message || r)
      clearUserInfo()
      return  router.push({ name: 'login' })
    case 201: 
      return router.push({ name: 'FirstChange' }) 
    case 403:
      message.error(r?.data?.message || r)
      return false
    case 200: 
      return r.data
    default: 
      return r
  } 
}, err => {
  message.error(err?.response?.data?.message || err.message || err)
  return false
})
//  建立一般请求
export const createRequest = (options) => {
  if (options.method) {
    options.method = options.method.toLowerCase()
  }
  let opt = {
    method: 'get'
  }
  for (const key in options) {
    opt[key] = options[key]
  }
  return instance(opt)
}
//  建立流式请求-已废弃
export const createSSERequest = (options, callback) => {
  if (options.method) {
    options.method = options.method.toLowerCase()
  }
  let opt = {
    method: 'get'
  }
  for (const key in options) {
    opt[key] = options[key]
  }
  let url = opt.url || ''
  if (!url) {
    return;
  }
  // opt.headers.token = `${token}`
  opt.headers['token'] = getToken()

  delete opt.url
  console.log(opt, 'opt')
  let time_delay = 0
  return fetchEventSource(BASE_URL + url, {
    ...opt,
    async onopen(response) {
      console.log(response,  response.headers.get('content-type'), 'response')
      if (response.ok && response.headers.get('content-type').includes('text/event-stream')) {
        return; // everything's good
      }
      //  else if (response.status >= 400 && response.status < 500 && response.status !== 429) {
      //   return new Error('参数错误！')
      // } else {
      //   return new Error('服务器错误！')
      // }
      callback(false, '服务器错误')
    },
    onmessage(msg) {
      setTimeout(() => {
        // 屎上暴力中断流式输出
        if (options.signal.aborted) return callback(false, '')
        //  屎上最暴力的流式输出，我真蚌埠住了，但没逝，code running || man running
        callback && callback(JSON.parse(msg.data))
      }, (++time_delay) * 50)
    },
    onclose(msg) {
      console.log('关闭')
      console.log(msg)
    },
    onerror(err) {
      callback(false, '连接错误')
      throw new Error('停止重连')
    }
  })
}

//  建立流式请求
export const useSSE = ({url, data = {}, callback, signal}) => {
  let body = {
    conversationId: data?.conversation_id || data?.conversationId,
    query: data?.query,
    inputs: {
      // languagePreference: 'zh_CN',
      languagePreference: lang.value,
      ...data?.inputs,
    }
  }
  let req = {
    method: data?.method?.toLowerCase() || 'post',
    body: JSON.stringify(body),
    signal,
    headers: {
      'Content-Type': 'application/json',
      'Accept': 'text/event-stream',
      'Accept-Language': getAcceptLanguage(),
      ...data.headers,
      'token': getToken(),
    },
    openWhenHidden: true
  }
  let timeDelay = 0
  console.log(signal.aborted, 'signal.aborted')

  return fetchEventSource(BASE_URL + url, {
    ...req,
    async onopen(response) {
      if (response.ok && response.headers.get('content-type').includes('text/event-stream')) return
      else if (response.status >= 400 && response.status < 500 && response.status !== 429) {
        // callback(false, t('request', '参数错误'))
        throw new Error(t('request', '参数错误'))
        // return new Error('参数错误！')
      }
      else {
        // callback(false, t('request', '服务器错误'))
        throw new Error(t('request', '服务器错误'))
        // return new Error('服务器错误！')
      }
    },
    onmessage(msg) {
      setTimeout(() => {
        // 屎上暴力中断流式输出
        if (signal.aborted) return callback(false)
        //  屎上最暴力的流式输出，我真蚌埠住了，但没逝，code running || man running
        callback && callback(JSON.parse(msg.data))
      },  (++timeDelay) * 40)
    },
    onclose() {
      // callback(false)
    },
    onerror(err) {
      callback(false, `${t('request', '停止重连,请稍后重试')},${err}`)
      userCheck()
      signal.aborted = true
      throw new Error()
    }
  })
}
